package com.eqdd.yiqidian.ui.share;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.RecyclerViewFragmentCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.SelectBean;
import com.eqdd.yiqidian.bean.rebuild.DepartmentListResultBean;
import com.eqdd.yiqidian.bean.rebuild.EmploymentListResultBean;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.utils.ListUtil;
import com.eqdd.yiqidian.utils.ReflectUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okrx2.adapter.FlowableBody;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.functions.BiFunction;
import io.rong.imlib.model.Conversation;

/**
 * Created by lvzhihao on 17-5-15.
 */

public class ShareWorkMateFragment extends BaseFragment {
    private RecyclerViewFragmentCustom databinding;

    private DepartmentListResultBean departmentListResultBean;

    private SlimAdapterEx slimAdapterEx;
    private DepartmentListResultBean departmentChoose;
    private ArrayList<Object> datas = new ArrayList<>();
    private List<DepartmentListResultBean> departList = new ArrayList<>();
    private List<SelectBean> employList = new ArrayList<>();

    @Override
    protected void setView() {
        if (slimAdapterEx == null) {
            databinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

            slimAdapterEx = SlimAdapterEx.create().register(R.layout.item_edit_title_type, new SlimInjector<String>() {
                @Override
                public void onInject(String data, IViewInjector injector) {
                    injector.text(R.id.tv_top_title, data);
                }
            }).register(R.layout.list_item_section, new SlimInjector<DepartmentListResultBean>() {
                @Override
                public void onInject(DepartmentListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_name, data.getDepartName());
                }
            }).register(R.layout.list_item_04, new SlimInjector<SelectBean>() {
                @Override
                public void onInject(SelectBean data, IViewInjector injector) {
                    injector.text(R.id.tv_content, data.getContent())
                            .imageCircle(R.id.iv_head, data.getHeadImg())
                            .checked(R.id.checkbox, data.isChecked())
                            .enable(R.id.checkbox, data.isEnable())
                            .text(R.id.tv_right, data.isEnable() ? "" : ShareWorkMateActivity.shareConf.getEnableTip());
                }
            }).attachTo(databinding.recyclerView);
            ItemClickSupport.addTo(databinding.recyclerView).setOnItemClickListener((rv, p, v) -> {

                if (slimAdapterEx.getData().get(p) instanceof DepartmentListResultBean) {
                    departmentChoose = (DepartmentListResultBean) slimAdapterEx.getData().get(p);
                    ((ShareWorkMateActivity) getActivity()).addFragment(departmentChoose);
                } else if (slimAdapterEx.getData().get(p) instanceof SelectBean) {
                    SelectBean bean = (SelectBean) slimAdapterEx.getDataItem(p);
                    if (bean.isEnable()) {
                        ArrayList<SelectBean> selectBeans = ShareWorkMateActivity.selectedBeans;
                        if (!bean.isChecked() && ShareWorkMateActivity.shareConf.getMaxNum()!=-1&&selectBeans.size() >= ShareWorkMateActivity.shareConf.getMaxNum()) {
                            ToastUtil.showShort(String.format(ShareWorkMateActivity.shareConf.getMaxTip(),ShareWorkMateActivity.shareConf.getMaxNum()));
                            return;
                        }
                        bean.setChecked(!bean.isChecked());
                        if (bean.isChecked()) {
                            selectBeans.add(bean);
                        } else {
                            selectBeans.remove(bean);
                        }
                        slimAdapterEx.notifyItemChanged(p);
                    }
                }
            });
        }
        refresh();
    }

    public void refresh() {
//        ((BaseActivity) getActivity()).showLoading();
        departList.clear();
        employList.clear();
        Flowable<HttpResult<List<DepartmentListResultBean>>> departFlow = OkGo.<HttpResult<List<DepartmentListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.Select_SECTION)
                .params("ParentId", departmentListResultBean.getDepartId())
                .params("CompanyId", departmentListResultBean.getCompanyId())
                .converter(new JsonConverter<HttpResult<List<DepartmentListResultBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<List<DepartmentListResultBean>>>());
        Flowable<HttpResult<List<EmploymentListResultBean>>> employmentFlow = OkGo.<HttpResult<List<EmploymentListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.SELECT_EMPLOYMENT)
                .params("departId", departmentListResultBean.getDepartId())
                .params("companyId", departmentListResultBean.getCompanyId())
                .converter(new JsonConverter<HttpResult<List<EmploymentListResultBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<List<EmploymentListResultBean>>>());
        Flowable.combineLatest(departFlow, employmentFlow, new BiFunction<HttpResult<List<DepartmentListResultBean>>, HttpResult<List<EmploymentListResultBean>>, Object>() {
            @Override
            public Object apply(HttpResult<List<DepartmentListResultBean>> listHttpResult, HttpResult<List<EmploymentListResultBean>> listHttpResult2) throws Exception {
                departList = listHttpResult.getItems();
                Flowable.fromIterable(listHttpResult2.getItems())
                        .subscribe(bean -> {
                            SelectBean selectBean = new SelectBean();
                            if (ShareWorkMateActivity.shareConf.getEnabledBeans() != null) {
                                for (Object o : ShareWorkMateActivity.shareConf.getEnabledBeans()) {
                                    if (ReflectUtil.getField(o, ShareWorkMateActivity.shareConf.getGuidField()).equals(bean.getGuid())) {
                                        selectBean.setEnable(false);
                                        break;
                                    }
                                }
                            }
                            selectBean.setContent(bean.getStaffName());
                            selectBean.setType(Conversation.ConversationType.PRIVATE);
                            selectBean.setGuid(bean.getGuid());
                            selectBean.setHeadImg(bean.getIphoto());

                            for (SelectBean selectedBean : ShareWorkMateActivity.selectedBeans) {
                                if (selectedBean.getGuid().equals(selectBean.getGuid())) {
                                    employList.add(selectedBean);
                                    return;
                                }
                            }
                            employList.add(selectBean);
                        });
                return 1;
            }
        })
                .subscribe((s) -> {
                    datas.clear();
                    if (!ListUtil.isEmpty(departList)) {
                        datas.add("部门");
                        datas.addAll(departList);
                    }
                    if (!ListUtil.isEmpty(employList)) {
                        datas.add("人员");
                        datas.addAll(employList);
                    }
                    slimAdapterEx.updateData(datas);
                }, e -> {
                    ToastUtil.showShort(Config.SERVER_ERROR);
                    System.out.println(e.toString());
//                    ((BaseActivity) getActivity()).hideLoading();
                }, () -> {
//                    ((BaseActivity) getActivity()).hideLoading();
                });
    }

    @Override
    protected void initData() {
        Bundle arguments = getArguments();
        departmentListResultBean = arguments.getParcelable(Config.DEPARTMENT);
    }


    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return databinding = DataBindingUtil.inflate(inflater, R.layout.fragment_recycler_view, null, false);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
